import { NextFunction, Request, Response } from 'express';
import { Logger } from '@nestjs/common';
import { UnauthorizedException } from '../exception/apiException';
import { WhitelistService } from '../common/whitelist/whitelist.service';

// 创建白名单服务实例
const whitelistService = new WhitelistService();
const logger = new Logger('AuthorizeMiddleware');

export const AuthorizeMiddleware = function (
  req: Request,
  res: Response,
  next: NextFunction,
) {
  try {
    const path = req.path;
    const method = req.method;
    const hasToken = !!req.headers.authorization;

    // 记录请求信息（调试模式）
    logger.debug(
      `Processing request: ${method} ${path}, hasToken: ${hasToken}`,
    );

    // 开发环境放行（如需要可取消注释）
    if (process.env.NODE_ENV === 'development') {
      logger.debug('Development environment - bypassing authorization');
      next();
      return;
    }

    // 检查是否在白名单中
    if (whitelistService.isWhitelisted(path, method)) {
      logger.log(`Whitelist access granted: ${method} ${path}`);
      next();
      return;
    }

    // 检查是否有授权token
    if (!hasToken) {
      logger.warn(
        `Unauthorized access attempt: ${method} ${path} - No token provided`,
      );
      throw new UnauthorizedException();
    }

    // token存在，继续处理
    logger.debug(`Token found for protected route: ${method} ${path}`);
    next();
  } catch (error) {
    // 确保异常被正确传递
    next(error);
  }
};
